package com.cloud.security.handler;

import cn.hutool.core.date.DatePattern;
import com.cloud.enums.SecurityEnum;
import com.cloud.pojo.sys.Result;
import com.cloud.pojo.user.UserInfo;
import com.cloud.service.LoginService;
import com.cloud.util.SecurityHandlerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登录成功处理逻辑
 */
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private LoginService loginService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = ((UserDetails) principal).getUsername();
        UserInfo userInfo = loginService.findUserByUsername(username);
        Date lastLoginTime = null == userInfo.getLastLoginTime() ? userInfo.getCreateTime() : userInfo.getLastLoginTime();
        String msgContent = String.format(SecurityEnum.LOGIN_SUCCESS.getDesc(), DatePattern.NORM_DATETIME_FORMAT.format(lastLoginTime));
        if(null != userInfo.getExpireTime()) {
            msgContent += String.format("  观影过期时间: %s", DatePattern.NORM_DATETIME_FORMAT.format(userInfo.getExpireTime()));
        }
        SecurityHandlerUtil.responseHandler(response,
                        Result.createFail(SecurityEnum.LOGIN_SUCCESS.getCode(), msgContent));
    }
}
